package com.scale.service.ai.service.impl;

import com.example.character.entity.AiCharacters;
import com.scale.service.ai.service.AIModelService;
import com.scale.service.character.service.AiCharactersService;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.InputRequiredException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * AI模型服务实现类
 * @author crp
 * @since 2025-09-24
 */
@Service
public class AIModelServiceImpl implements AIModelService {

    @Autowired
    private AiCharactersService aiCharactersService;

    @Value("${ai.model.provider:qwen}")
    private String aiProvider;

    @Value("${ai.model.name:qwen-turbo}")
    private String defaultModelName;

    @Value("${ai.context.max-messages:10}")
    private Integer maxContextMessages;
    
    @Value("${dashscope.api-key:}")
    private String dashscopeApiKey;

    @Override
    public String getAIReply(AiCharacters character, String userMessage, String conversationHistory, Long userId) {
        try {
            // 根据配置的AI服务提供商调用不同的模型
            switch (aiProvider.toLowerCase()) {
                case "qwen":
                case "tongyi":
                    return callTongyiModel(character, userMessage, conversationHistory, userId);
                case "openai":
                case "chatgpt":
                    return callOpenAIModel(character, userMessage, conversationHistory, userId);
                case "claude":
                    return callClaudeModel(character, userMessage, conversationHistory, userId);
                default:
                    return generateDefaultReply(character, userMessage);
            }
        } catch (Exception e) {
            System.err.println("AI模型调用失败: " + e.getMessage());
            return generateDefaultReply(character, userMessage);
        }
    }

    @Override
    public String buildConversationContext(Long characterId, Long userId, String currentMessage) {
        // 获取角色信息
        AiCharacters character = aiCharactersService.getById(characterId);
        if (character == null) {
            return currentMessage;
        }

        // 构建简单的对话上下文
        StringBuilder context = new StringBuilder();

        // 添加角色系统提示
        if (character.getSystemPrompt() != null && !character.getSystemPrompt().isEmpty()) {
            context.append("系统提示: ").append(character.getSystemPrompt()).append("\n\n");
        }

        // 添加角色人设
        context.append("角色设定:\n");
        context.append("- 名称: ").append(character.getName()).append("\n");
        context.append("- 性格: ").append(character.getPersonality()).append("\n");
        context.append("- 背景: ").append(character.getBackground()).append("\n\n");

        // 添加当前消息
        context.append("用户: ").append(currentMessage).append("\n");
        context.append(character.getName()).append(": ");

        return context.toString();
    }

    /**
     * 调用通义千问模型
     */
    private String callTongyiModel(AiCharacters character, String userMessage, String conversationHistory, Long userId) {
        try {
            Generation gen = new Generation();

            // 构建消息列表
            List<Message> messages = new ArrayList<>();

            // 添加系统消息（角色人设）
            String systemPrompt = buildSystemPrompt(character);
            messages.add(Message.builder()
                    .role(Role.SYSTEM.getValue())
                    .content(systemPrompt)
                    .build());

            // 添加对话历史
            if (conversationHistory != null && !conversationHistory.isEmpty()) {
                parseAndAddConversationHistory(messages, conversationHistory, character.getName());
            }

            // 添加当前用户消息
            messages.add(Message.builder()
                    .role(Role.USER.getValue())
                    .content(userMessage)
                    .build());

            // 检查API密钥
            String apiKey = getApiKey();
            if (apiKey == null || apiKey.trim().isEmpty()) {
                throw new RuntimeException("API密钥未配置，请设置DASHSCOPE_API_KEY环境变量");
            }

            GenerationParam param = GenerationParam.builder()
                    .apiKey(apiKey)
                    .model(defaultModelName)
                    .messages(messages)
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .topP(0.8) // 控制生成的随机性
                    .temperature(0.7f) // 控制创造性
                    .maxTokens(1000) // 限制回复长度
                    .build();

            GenerationResult result = gen.call(param);

            if (result != null && result.getOutput() != null && result.getOutput().getChoices() != null) {
                String aiReply = result.getOutput().getChoices().get(0).getMessage().getContent();
                return postProcessAIReply(aiReply, character);
            }

            return generateContextualReply(character, userMessage, conversationHistory);

        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("通义千问调用失败: " + e.getMessage());
            return generateContextualReply(character, userMessage, conversationHistory);
        }
    }

    /**
     * 构建系统提示词
     */
    private String buildSystemPrompt(AiCharacters character) {
        StringBuilder systemPrompt = new StringBuilder();

        // 基础角色设定
        systemPrompt.append(String.format("你是%s，", character.getName()));

        if (character.getPersonality() != null && !character.getPersonality().isEmpty()) {
            systemPrompt.append(String.format("性格特点：%s。", character.getPersonality()));
        }

        if (character.getBackground() != null && !character.getBackground().isEmpty()) {
            systemPrompt.append(String.format("背景：%s。", character.getBackground()));
        }

        // 添加自定义系统提示
        if (character.getSystemPrompt() != null && !character.getSystemPrompt().isEmpty()) {
            systemPrompt.append(character.getSystemPrompt());
        }

        // 添加通用行为指导
        systemPrompt.append("\n请保持角色一致性，用温暖、耐心的语气与用户交流。");
        systemPrompt.append("回复要简洁明了，避免过长的回答。");
        systemPrompt.append("如果用户情绪低落，要给予关怀和支持。");

        return systemPrompt.toString();
    }

    /**
     * 解析对话历史并添加到消息列表
     */
    private void parseAndAddConversationHistory(List<Message> messages, String conversationHistory, String characterName) {
        if (conversationHistory == null || conversationHistory.isEmpty()) {
            return;
        }

        // 简单的对话历史解析（假设格式为：用户: xxx\n角色名: xxx\n）
        String[] lines = conversationHistory.split("\n");
        for (String line : lines) {
            if (line.trim().isEmpty()) continue;

            if (line.startsWith("用户: ")) {
                String content = line.substring(3).trim();
                if (!content.isEmpty()) {
                    messages.add(Message.builder()
                            .role(Role.USER.getValue())
                            .content(content)
                            .build());
                }
            } else if (line.startsWith(characterName + ": ")) {
                String content = line.substring(characterName.length() + 2).trim();
                if (!content.isEmpty()) {
                    messages.add(Message.builder()
                            .role(Role.ASSISTANT.getValue())
                            .content(content)
                            .build());
                }
            }
        }
    }

    /**
     * 后处理AI回复
     */
    private String postProcessAIReply(String aiReply, AiCharacters character) {
        if (aiReply == null || aiReply.isEmpty()) {
            return generateDefaultReply(character, "");
        }

        // 移除可能的前缀（如角色名）
        String characterName = character.getName();
        if (aiReply.startsWith(characterName + ":") || aiReply.startsWith(characterName + "：")) {
            aiReply = aiReply.substring(characterName.length() + 1).trim();
        }

        // 限制回复长度
        if (aiReply.length() > 500) {
            aiReply = aiReply.substring(0, 497) + "...";
        }

        return aiReply;
    }

    /**
     * 调用OpenAI模型
     */
    private String callOpenAIModel(AiCharacters character, String userMessage, String conversationHistory, Long userId) {
        // TODO: 集成OpenAI API
        return generateContextualReply(character, userMessage, conversationHistory);
    }

    /**
     * 调用Claude模型
     */
    private String callClaudeModel(AiCharacters character, String userMessage, String conversationHistory, Long userId) {
        // TODO: 集成Anthropic Claude API
        return generateContextualReply(character, userMessage, conversationHistory);
    }

    /**
     * 生成默认回复（降级方案）
     */
    private String generateDefaultReply(AiCharacters character, String userMessage) {
        String characterName = character.getName();
        String personality = character.getPersonality();

        return String.format("作为%s，我理解你的想法。%s 让我们来讨论一下这个问题。",
               characterName, personality != null ? personality : "");
    }

    /**
     * 生成有上下文的回复
     */
    private String generateContextualReply(AiCharacters character, String userMessage, String conversationHistory) {
        String characterName = character.getName();
        String personality = character.getPersonality();

        // 根据对话历史生成更智能的回复
        if (conversationHistory != null && conversationHistory.contains("你好")) {
            return String.format("很高兴继续和你聊天！作为%s，%s", characterName,
                   personality != null ? personality + "我想了解你今天怎么样？" : "我在这里倾听你。");
        }

        return String.format("作为%s，我理解你的想法。%s 让我们深入聊聊这个话题。",
               characterName, personality != null ? personality : "");
    }
    
    /**
     * 获取API密钥（优先使用配置文件，其次使用环境变量）
     */
    private String getApiKey() {
        // 优先使用配置文件中的API密钥
        if (dashscopeApiKey != null && !dashscopeApiKey.trim().isEmpty()) {
            return dashscopeApiKey.trim();
        }
        
        // 其次使用环境变量
        String envApiKey = System.getenv("DASHSCOPE_API_KEY");
        if (envApiKey != null && !envApiKey.trim().isEmpty()) {
            return envApiKey.trim();
        }
        
        return null;
    }

}
